



//界面组件


/**
 *日历工具 
 */
var calendar={
	obj:null,
	main:null,
	
	currentYear:null,
	currentMonth:null,
	currentDay:null,

	preYear:null,
	preMonth:null,
	
	nextYear:null,
	nextMonth:null,
	
	dayList:null,
	
	init:function(){
		this.main = $("<div />").addClass("n-calendar-pad")
			.append(
				$("<dt />").addClass("calendar-head")
				.append(
					$("<div />").addClass("calendar-date")
						.append($("<a />").addClass("calendar-year-pre").text("<").click(function(){--calendar.currentYear;calendar.fresh();}))
						.append($("<span />").addClass("calendar-year").text("2012"))
						.append($("<a />").addClass("calendar-year-next").text(">").click(function(){++calendar.currentYear;calendar.fresh();}))
						.append($("<a />").addClass("calendar-month-pre").text("<").click(function(){
															if(calendar.currentMonth>1){
																--calendar.currentMonth;
															}else{
																calendar.currentMonth=12;
																--calendar.currentYear;
															}
															calendar.fresh();
														})
													)
						.append($("<span />").addClass("calendar-month").text("01"))
						.append($("<a />").addClass("calendar-month-next").text(">").click(function(){
															if(calendar.currentMonth<12){
																++calendar.currentMonth;
															}else{
																calendar.currentMonth=1;
																++calendar.currentYear;
															}
															calendar.fresh();
														})
													)
				)
				.append($("<div />").addClass("calendar-week")
					.append($("<span />").text("一"))
					.append($("<span />").text("二"))
					.append($("<span />").text("三"))
					.append($("<span />").text("四"))
					.append($("<span />").text("五"))
					.append($("<span />").text("六"))
					.append($("<span />").text("日"))
				)
			)
			.append(
				$("<dd />").addClass("calendar-day")					
			)
			.hide()
			.appendTo('body');
				

			
	},

	close:function(){
		//linruiyan@2012-10-7 fadeTo只是把层透明了。而不会display:none，导致关闭后还能得到焦点，影响底层空间获取焦点
		//this.main.fadeTo("slow",0);
		
		this.main.hide();
	},
	select:function(){},
	
	preYear:function(){},
	nextYear:function(){},
	preMonth:function(){},
	nextYear:function(){},
	
	fresh:function(){
		if(!calendar.currentYear || !calendar.currentMonth){
			var today = new Date();
			calendar.currentYear = today.getUTCFullYear();
			calendar.currentMonth = today.getUTCMonth()+1;
			calendar.currentDay = today.getUTCDate();			 
		}
		this.main.find('.calendar-year').html(calendar.currentYear);
		this.main.find('.calendar-month').html(calendar.currentMonth);
		
		this.main.find("dd").html('');
		//linruiyan@2012-10-8 统一按字面上的数字为月数。参数自己减一来处理
		var day = new Date(calendar.currentYear,calendar.currentMonth,0);
		var firtday = new Date(calendar.currentYear,calendar.currentMonth-1,1).getUTCDay()+1;
		//alert(firtday);
		//linruiyan@2012-10-8 如果当月的1号是星期一，那么将跳过下面的循环。i不被初始化。导致在循环高亮周末时失效。
		//						所以将i的初始化拿到外面来。
		var i=1;
		if(firtday<=7){
			for(;i<firtday;i++){
				this.main.find("dd").append(($("<span />").html(i)));
			}
		}
		var w=i;

		var totalday = day.getDate();
		for(var i=1;i<=totalday;i++){
			
			var item = $("<a />").html(i);
			if(i==this.currentDay){
				item.addClass("current");
			}
			w = ++w%7;
			if(1==w || 0==w){
				item.addClass("weekend");
			}
			this.main.find("dd").append(item);				
		}
		this.main.find("dd a").click(function(){
			$(calendar.main.find("dd a.current").removeClass("current"));
			$(this).addClass("current");
			
			var month = '00'+$(calendar.main).find('.calendar-month').html();
			var day = '00'+$(this).html();
			$(calendar.obj).val($(calendar.main).find('.calendar-year').html()+'-'+month.substr(-2)+'-'+day.substr(-2));
		});
		this.main.stop(true,false).show();
	},
	under:function(obj){
		var popHandle = $(obj).parents('.ply-html');
		var offset = $(obj).position();
		if(popHandle.length){
			this.main.css({"zIndex":popHandle.css("zIndex")+1});
			ui.closeCallback = function(){calendar.close();};
			offset.left = offset.left + parseInt(popHandle.css('left'))+6;
			offset.top = offset.top + parseInt(popHandle.css('top'))+8;
		}else{
			
		}
		
		this.obj = obj;
		this.main.stop();
		this.fresh();
		$(this.main).css({left:offset.left,top:offset.top+$(obj).outerHeight()-parseInt($(obj).css("border-width"))});
		
	}
};
$(document).ready(function(){
	calendar.init();
	
	$(".n-calendar").mousedown(function(){

		var ymd = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec($(this).val());
		if(ymd!=null){
			calendar.currentYear = ymd[1];
			calendar.currentMonth = parseInt(ymd[2]);
			calendar.currentDay = ymd[3];
		}
		calendar.under(this);
		// alert(1)
		// alert(calendar.main.html())
	});
	$(calendar.main).mouseover(function(){
		$(calendar.main).stop().show();
	});
	$(calendar.main).mouseout(function(){
		calendar.close();
	});
});










var reui ={
	init:{
		handles:[],
		reg:function(func){
			this.handles.append(func);
		},
		start:function(){
			for(var i in this.handles){
				eval(this.handles[i]);
			}
		}
	}
};


jQuery.extend(reui);
$(document).ready(function(){
	$.init.start();
});

/**
 *表格工具 
 */

$(document).ready(function(){
	$(".n-table").each(function(){
		var line = 1;
		$(this).find("tbody tr").each(function(){
			$(this).hover(function(){
				$(this).addClass("bright");
			},function(){
				$(this).removeClass("bright");
			});
			if(1==line){
				$(this).addClass("odd");
			}else{
				$(this).addClass("even");
			}
			line = 1-line;
			
			
		});
	});
});

function saveExcel(sheet,obj){
	
	var form = $("<form>")
			form.attr("method",'POST')
				.attr("action",'/phpexcel/create.html')
				.attr("target","pajax");
	var sheetInput = $("<input>").attr("name","sheet").attr("value",sheet);	
	form.append(sheetInput);




	var i=0,j=0;

	$(obj).find("tr").each(function(){
		
		j = 0;
		$(this).children().each(function(){
			if(!$(this).hasClass('excel-ignore')){

				$("<input>")
					.attr("name","data["+i+"]["+j+"]")
					.attr("value",$(this)[0].tagName+'T&V'+$(this).text())
					.appendTo(form);	
			}
			j++;
		});

		i++;
	});



	form.submit();
}



/**
 * 搜索框工具
 */
$(document).ready(function(){
	$('.n-search').each(function(){
		var tips = $(this).attr('tips')?$(this).attr('tips'):'请输入';
		
		$(this).parents('form').submit(function(){
			$(this).find(".n-search").each(function(){
				if($(this).val()==$(this).attr('tips')){
					$(this).val('');
				}
			});
		});
		

		if(''==$(this).val()){
			$(this).val(tips).removeClass("n-search-input");
		}

		$(this).focusin(function(){
			if($(this).val()==tips){
				$(this)
					.val('')
					.removeClass("n-search-input");
			}else{
				$(this)
					.addClass("n-search-input");
			}

		});
		//linruiyan@2012-10-7 当输入时，只要不是为空，那么就会设置为主字体颜色
		$(this).keyup(function(){
			if($(this).val()==tips){
				$(this)
					.removeClass("n-search-input");
			}else{
				$(this)
					.addClass("n-search-input");
			}
		});
		$(this).focusout(function(){
			if(''==$(this).val()){
				$(this)
					.val(tips)
					.removeClass("n-search-input");
			}else{
				$(this)
					.addClass("n-search-input");
			}
		});
	});
});


/**
 *拖拽框 
 */

var dropli = {
	handle:{},
	project:{},
	data:{},
	init:function(){
	
		for(var i in this.data){
			// alert(this.data[i].id);
			//alert("<li>"+this.data[i].title+"</li>");
			$('#n-dropli').append(this.createItem('【'+this.data[i].pname+'】'+this.data[i].name,this.data[i].id))
			//$('#n-dropli').append("<li>"+this.data[i].title+"</li>");
		}
		this.handle = $('#n-dropli');
		$('#n-dropli').height($('#n-dropli').height());//高度不固定，最下面一个分类会出现屏幕抖动问题
	},
	createItem:function(title,val){
		return $("<li>").text(title)
				.attr('val',val)
				.addClass(val?'private-cate':'common-cate')
				.mousedown(function(e){
					$(this)
							.addClass("refix")
							.addClass("moveing")
					
							//.css({position:'absolute'})
							// .css({'zIndex':dropli.handle.css("zIndex")+1})
// alert(dropli.handle.find("li").length)
					var lastY = e.originalEvent.y || e.originalEvent.layerY || 0;
					
					$(this)
						.mousemove(function(e) { 
							var xx = e.originalEvent.x || e.originalEvent.layerX || 0; 
							var yy = e.originalEvent.y || e.originalEvent.layerY || 0;
							
							// alert(dropli.handle.offset()['top'])
							var offset = yy+$(document).scrollTop();
							// alert(offset);
							$(this).offset({top:offset-10});
							//顶部有面包屑，需要空开
							var replaceItemSeq = Math.ceil((offset-dropli.handle.offset()['top'])/24)-1;
							var itemLen = dropli.handle.find("li").length;
							if(replaceItemSeq>=itemLen){
								replaceItemSeq = itemLen-1;
							}
							// $("#info").html(replaceItemSeq)
							var replaceItem = $(dropli.handle.find("li")[replaceItemSeq]);
							if($(this).attr("val")!=replaceItem.attr("val")){
								//alert(1);
								var newitem = replaceItem.clone(true);
								// $("#info").html(yy%22)
								
								if(yy>lastY){
									$(this).before(newitem);
								}else{
									$(this).after(newitem);	
								}
								lastY = yy;
								
								replaceItem.detach();
							}
						})

				})
				.mouseup(function(){
					$(this)
							.removeClass("moveing")
							.css({top:'auto',left:'auto'})
					$(this).unbind('mousemove');
				})

				.mouseout(function(){
					$(this)
							.mouseup();
				})
	
	}

	
}



function selector(obj,cb){
	
	var that = this;
	var main = $("<ul>")
					.addClass("selector-list")
					.appendTo("body")
					.hide()
					.mouseover(function(){
						lostfocus = 'N';
					})
					.mouseout(function(){
						lostfocus = 'Y';
					})
	

	var input = $(obj)
					.attr("autocomplete","off")
					.keyup(function(e){
						if(-1!=$.inArray(e.keyCode,[37,39])){
							
						}else if(e.keyCode==38){
							preSelected('up');
						}else if(e.keyCode==40){
							preSelected('down');
						}else if(e.keyCode==13){
							var preItem = main.find(".pre-selected");
							if(0<preItem.length){
								preItem.click();
							}
						}else{
							search($(this).val());
							
						}
					})
					.focusout(function(){
						//alert(lostfocus);
						if('Y'==lostfocus){
							main.hide();
						}
					});

	var lostfocus = 'Y';
	var autoclose = 'Y'==input.attr("autoclose")?true:false;
	
	var url = input.attr('url');
	
	var disabled=[],ignore=[],only=[];
	
	this.toDisabled=function(list){disabled = $.merge(disabled,list)};
	this.toIgnore=function(list){ignore = $.merge(ignore,list)};
	this.toOnly=function(list){only = $.merge(only,list)};
	
	this.init=function(ids){
		if(''!=ids){
			$.getJSON(url,{ids:ids},function(data){
				$(data).each(function(){
					var i = $("<div>").data("data",this)
					that.callback(i);
					disabled.push(this.id);
				});
			});
		}		
	};
	
	function selected(obj){
		$(obj).click(function(){
			if(!$(obj).hasClass("disabled")){
				that.callback(this);
				if(autoclose){
					main.hide();
					input.val('');
				}
				disabled.push($(obj).data('data').id);
				/**
				var d = [];
				d.push($(obj).data('data').id);
				that.toDisabled(d);
				 */
				input.focus();
			}
		});
	}	

	function preSelected(direct){
		var current = main.find(".pre-selected")
		var nextItem = null;
		if('up'==direct){
			var nextItem = current.prev();
			if(0==current.length || 0==nextItem.length){
				nextItem = main.find("li:last");
			}
		}else if('down'==direct){
			var nextItem = current.next();
			if(0==current.length && 0==nextItem.length){
				nextItem = main.find("li:first");
			}
		}else{
			nextItem = direct;
		}
		
		main.find(".pre-selected").removeClass("pre-selected");
		nextItem.addClass("pre-selected");
		//console.log(input.attr('id'));
		input.val(nextItem.text());
	}

	function getState(id){
		ppid = parseInt(id);
		if(-1!=$.inArray(id,only)){
			return 'only';
		}else if(-1!=$.inArray(id,ignore)){
			return 'ignore';
		}else if(-1!=$.inArray(id,disabled)){
			return 'disabled';	
		}else{
		}
		return 'normal';
	}
	function search(key){
		if(''==key){
			fresh([]);
		}else{
			$.getJSON(url,{key:key,only:only,ignore:ignore},function(data){
				fresh(data);
			});
		}
	}
	function fresh(data){
		
		main.html('');
		
		if(0==data.length){
			main.hide();
		}else{
			$(data).each(function(){
				var item = this
				var state = getState(item.id);
				if(-1!=$.inArray(state,['normal','disabled'])){
					var itemNode = itemHtml(item,state);
					itemNode.data("data",item)
					itemNode.mouseover(function(){
						preSelected($(this))
					});
					selected(itemNode);
					main.append(itemNode);
					
				}
			});
			main.show();
			
			var offset = input.offset();
			offset.top = offset.top+input.height();
			main.offset(offset)
			
		}
	}
	function itemHtml(item,state){
		var li = $("<li>")
						//.addClass(state)   //如何pop指定数组的值没有合适的方案。所以暂时去掉disable功能
						.mouseover(function(){
							preSelected($(this))
						})
		$("<span>")
				//.attr("href","javascript:void(0)")
				.text(item.name)
				//.addClass('online-'+isonline)
				.appendTo(li);
		return li;
	}

	//function callback(){}
//alert(input.attr("callback"));
	this.callback= undefined==input.attr("callback")?function(obj){}:eval(input.attr("callback"))
	//var callback = eval(input.attr("callback"))
	//this.callback = cb;
	

};


/**
 *鼠标滑过时出现工具栏下过 
 */
var hoverToolsBar = {
	
	init:function(){
		$(".n-hover-toolbar").each(function(){
			var that = this;
			$(this)
				.hide()
				.parent()
					.css({position:"relative"})
					.hover(function(){
							$(that).show();
						},function(){
							if($(this).find('.n-hover-toolbar .n-focus').length==0){
								$(that).hide();
							}
						});
		});
	}
	
};
$(document).ready(function(){
	hoverToolsBar.init();
});


/**
 *linruiyan@2014年11月20日
 * js前端内容检索 
 */

var searchLi = {
	
	handle:null,
	selector:'',
	init:function(){
		this.handle = $("#n-search-li");
		this.selector = this.handle.attr('selector');
		this.handle
			.keyup(function(){
				searchLi.search();
			})
			.change(function(){
				searchLi.search();
			})
			
	},
	search:function(){
		
		var kw = this.handle.val();
		$(this.selector + " li")
					.removeClass('n-show')	
					.removeClass('n-hide');	
		if(kw!=''){
			$(this.selector + " li")
					.addClass('n-hide');	
			$(this.selector + " li:contains('"+kw+"')")
										.removeClass('n-hide')
										.addClass('n-show')
		}
	}
}
$(document).ready(function(){
	/*linruiyan@2014年11月20日 重写contains*/
	jQuery.expr[':'].contains = function(a, i, m) {
		return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
	};
	searchLi.init();
});
